/* Description: 写着玩的socket Server
 * Author: zhouhui
 * Release Date: 2014-10-22
 * Modify log: 
 */ 

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Usage: %s <ip_addr> <port>\n", argv[0]);
        return 1;
    }

    struct sockaddr_in si;
    si.sin_family = AF_INET;

    si.sin_port = htons(atoi(argv[2]));
    if (inet_pton(AF_INET,argv[1],&si.sin_addr.s_addr) == -1)
    {
        perror("inet_pton");
        return 1;
    }

    int sck = socket(AF_INET, SOCK_STREAM, 0);
    if (sck == -1)
    {
        perror("socket");
        return 1;
    }
 
    if (bind(sck, (struct sockaddr *)&si,sizeof(struct sockaddr_in)) == -1)
    {
        perror("bind");
        return 2;
    }

    if (listen(sck, 50) == -1)
    {
        perror("listen");
        return 2;
    }

    int asck;
    struct sockaddr_in clt_addr;
    socklen_t addr_len = sizeof(struct sockaddr_in);

    while(1)
    {
        if ((asck = accept(sck, (struct sockaddr *)&clt_addr, &addr_len)) == -1)
        {
            perror("accept");
            return 2;
        }

        char buf[1024] = {0};
        char *buf_p = buf;
        ssize_t readNum;
        while ((readNum = read(asck, buf_p, 1023)) > 0)
        {
            if (buf_p[0] == 4) //if peer socket type CTRL+D, buf_p[0] is EOT(assic code 4)
            { 
                close(asck);
                break;
            }
            buf_p += readNum;
        }

        buf_p[readNum] = 0;
        printf("%s\n---------------------\n",buf);
    }

    return 0;
}
